package com.mzj.saas.filter;


import com.mzj.saas.commons.MD5Utils;
import com.mzj.saas.commons.Constant;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class TokenUtil {
	private static Logger LOG = LoggerFactory.getLogger(TokenUtil.class);
	@Value("${manager.auth.header.token}")
	private String managerAuthHeaderToken;
	@Autowired
	@Qualifier("stringRedisTemplate")
	private StringRedisTemplate redisTemplate;

	@Value(value = "${redis.token.expire.time}")
	private Integer redisTokenExpireTime;// 过期时

	/**
	 * 外部应用调用接口token验证
	 * 
	 * @param accessToken
	 * @return
	 */
	public boolean externalTokenCheck(String accessToken) {
		boolean flag = false;
		try {
			if (!StringUtils.isBlank(accessToken)) {
				String redisToken = redisTemplate.opsForValue().get(accessToken);
				// LOG.info("ExternalTokenCheck accessToken = {},redisToken =
				// {}",accessToken,redisToken);
				if (redisToken != null) {
					flag = true;
				}
			}

			return flag;
		} catch (Exception e) {
			LOG.error("ExternalTokenCheck Exception = {}", e.getMessage());
		}
		return flag;

	}

	/**
	 * 后管请求校验
	 * 
	 * @param requestManagerAuthToken
	 * @return
	 */
	public boolean managerCheck(String requestManagerAuthToken) {
		boolean managerFlag = false;
		LOG.info("ManagerCheck requestManagerAuthToken = {}, managerAuthHeaderToken = {}", requestManagerAuthToken,
				managerAuthHeaderToken);
		if (!StringUtils.isBlank(requestManagerAuthToken) && requestManagerAuthToken.equals(managerAuthHeaderToken)) {
			managerFlag = true;
		}
		return managerFlag;
	}

	/**
	 * 根据openId获取token
	 * 
	 * @param openId
	 * @return
	 */
	public String authToken(String openId) {
		String tokenStr = openId + new Date().getTime();
		String md5Token = MD5Utils.MD5Encode(tokenStr, "UTF-8");
		String tokenKeyValue = Constant.LOGIN_TOKEN + ":" + md5Token;

		if (redisTemplate.opsForValue().get(tokenKeyValue) == null) { // 如果为空的时候,插入redis数据库
			redisTemplate.opsForValue().set(tokenKeyValue, tokenKeyValue, redisTokenExpireTime, TimeUnit.MINUTES);
			LOG.info("TokenUtil authToken redis save success, key = {}, value = {}", tokenKeyValue, tokenKeyValue);
		}
		return redisTemplate.opsForValue().get(tokenKeyValue);
	}

}
